package com.frank.demo.api;

import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 星座api
 * Created by zhy on 2018/5/7.
 */
public class Astro {

    private static final String host = "http://www.xzw.com/%s";
    private static final String default_path = "/fortune/cancer/";

    public static void main(String[] args) throws IOException, InterruptedException {
        new Astro().getAllData(false);
    }

    public void getAllData() throws IOException, InterruptedException {
        getAllData(false);
    }

    /**
     * @param isTest 是否为测试
     * @throws IOException
     * @throws InterruptedException
     */
    public void getAllData(boolean isTest) throws IOException, InterruptedException {
        Response response = Request.Get(String.format(host, default_path)).execute();

        Document document = Jsoup.parse(response.returnContent().toString());
//        System.out.println(document.body());
        Elements hrefs = document.select(".card_xingzuo a");
        for (Element href : hrefs) {
            String path = href.attr("href");
            getInfo(path);
            if (isTest) {
                break;
            }
            TimeUnit.MILLISECONDS.sleep(500);//怕被封ip
            System.out.println("--------------------------------------");
        }
    }

    /**
     * 自己用pojo封装吧，杠杠的
     * @param path
     * @throws IOException
     */
    public void getInfo(String path) throws IOException {

        Response response = Request.Get(String.format(host, path)).execute();

        Document document = Jsoup.parse(response.returnContent().toString());

        String name = document.select(".view dd h4").text();
        System.out.println(new StringBuilder(name).insert(7, "："));
//        System.out.println(document.body());
        Pattern p = Pattern.compile("\\d\\d");
        Elements details = document.select(".view dd li");
        for (Element detail : details) {
            System.out.print(detail.text());

            Matcher m = p.matcher(detail.select("em").attr("style"));
            if (m.find()) {
                System.out.println(Integer.valueOf(m.group()) / 16);
            } else {
                System.out.println();
            }
        }

        Elements c_conts = document.select(".c_cont p");
        for (Element c_cont : c_conts) {
            System.out.println(new StringBuilder(c_cont.text()).insert(4, "："));
        }
    }
}
